package com.wenhai.liuyubobobo.imooc.sort;

import static com.wenhai.liuyubobobo.imooc.sort.SelectionSort.swap;

/**
 * @ClassName InsertionSort
 * @Description 插入排序
 * @Author 谢文海
 * @Date 2021/2/19 19:42
 * @Version 1.0
 **/
public class InsertionSort {
    private InsertionSort() {
    }

    public static <E extends Comparable<E>> void sort(E[] e) {
        if (e == null || e.length <= 1) {
            return;
        }
        for (int i = 1; i < e.length; i++) {
            for (int j = i; j > 0 && e[j].compareTo(e[j - 1]) < 0; j--) {
                swap(e, j, j - 1);
            }
        }
    }

    public static <E extends Comparable<E>> void sort2(E[] e) {
        if (e == null || e.length <= 1) {
            return;
        }
        for (int i = 1; i < e.length; i++) {
            E t = e[i];
            int j;
            for (j = i; j > 0 && t.compareTo(e[j - 1]) < 0; j--) {
                e[j] = e[j - 1];
            }
            if (j != i) {
                e[j] = t;
            }
        }
    }

    public static <E extends Comparable<E>> void sort(E[] e, int from, int to) {

        if (e == null || e.length <= 1) {
            return;
        }
        for (int i = from + 1; i <= to; i++) {
            E t = e[i];
            int j;
            for (j = i; j > from && t.compareTo(e[j - 1]) < 0; j--) {
                e[j] = e[j - 1];
            }
            if (j != i) {
                e[j] = t;
            }
        }
    }

    public static <E extends Comparable<E>> void sort3(E[] e) {
        if (e == null || e.length <= 1) {
            return;
        }
        for (int i = e.length - 2; i >= 0; i--) {
            E t = e[i];
            int j;
            for (j = i; j < e.length - 1 && t.compareTo(e[j + 1]) > 0; j++) {
                e[j] = e[j + 1];
            }
            if (j != i) {
                e[j] = t;
            }
        }
    }
}
